package com.study.concurrency;

import java.util.concurrent.Semaphore;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

public class Playground {

	private Track[] tracks = {
			new Track(1),new Track(2),new Track(3),new Track(4),new Track(5)
	};
	
	private volatile boolean[] used = new boolean[5];
	private Semaphore semaphore = new Semaphore(5, true);  //最多同时有5个线程并发执行
	
	
	public Track getTrack() throws InterruptedException{
	
		semaphore.acquire(1);
		return getNextAvailableTrack();
	
	}

	public void releaseTrack(Track track){
		for (Track tmpTrack : tracks) {
			if(tmpTrack.getNum() == track.getNum()){
				if(used[track.getNum()-1]){
					used[track.getNum()-1] = false;
					semaphore.release();
				}
			}
		}
//		if(makeAsUsed(track)){
//			semaphore.release();
//		}
	}
	
	//遍历，找到一个没人用的跑道
	private Track getNextAvailableTrack() {
		for(int i = 0 ; i < used.length ; i++){
			if(!used[i]){
				used[i] = true;
				return tracks[i];
			}
		}
		return null;
	}
	
	//返回一个报道
	private boolean makeAsUsed(Track track){
		for(int i = 0 ; i < used.length; i++){
			if(tracks[i] == track){
				if(used[i]){
					used[i] = false;
					return true;
				}else {
					return false;
				}
			}
		}
		return false;
	}
}

@Slf4j
@Data
class Track {
	private int num;
	
	
	public Track(int num) {
		super();
		this.num = num;
	}

	@Override
	public String toString() {
		return "Track [num=" + num + "]";
	}
	
	
}